package com.ml.mall.service.order.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.bean.req.CouponListCheckReq;
import com.ml.mall.bean.req.credit.CreditRecordNewDto;
import com.ml.mall.bean.req.credit.CreditRecordQueryDto;
import com.ml.mall.bean.req.order.OrderPaymentDataQueryDto;
import com.ml.mall.bean.req.vo.*;
import com.ml.mall.bean.res.couppon.CoupponCheckRes;
import com.ml.mall.bean.vo.OrderDetailArrVO;
import com.ml.mall.bean.vo.coupon.CupponDetailVO;
import com.ml.mall.consts.OrderStateConsts;
import com.ml.mall.entity.coupon.SysCouponRecord;
import com.ml.mall.entity.delivery.SysOrderDelivery;
import com.ml.mall.entity.payinfo.SysPayinfo;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.mapper.company.SysCompanyMapper;
import com.ml.mall.mapper.coupon.SysCouponRecordMapper;
import com.ml.mall.service.addr.SysOrderAddrService;
import com.ml.mall.service.asyn.OrderMailServiceImplAsyn;
import com.ml.mall.enums.CreditEnum;
import com.ml.mall.service.company.SysCompanyAddrService;
import com.ml.mall.service.coupon.SysCouponRecordService;
import com.ml.mall.service.credit.SysCreditRecordService;
import com.ml.mall.service.credit.SysCreditService;
import com.ml.mall.service.delivery.SysOrderDeliveryService;
import com.ml.mall.service.msg.SysOrderMsgService;
import com.ml.mall.service.order.SysOrderCoupponService;
import com.ml.mall.service.payinfo.SysPayinfoService;
import com.ml.mall.service.state.SysOrderStateService;
import com.ml.mall.utils.*;
import com.ml.mall.bean.page.Page;
import com.ml.mall.bean.req.BaseBeanReq;
import com.ml.mall.bean.req.order.OrderEditReq;
import com.ml.mall.bean.req.order.OrderNewReq;
import com.ml.mall.bean.req.order.OrderQueryPageReq;
import com.ml.mall.bean.res.ShoppingCartQueryRes;
import com.ml.mall.bean.res.order.OrderQueryOneRes;
import com.ml.mall.bean.res.order.OrderQueryPageRes;
import com.ml.mall.bean.res.order.vo.OrderArrVO;
import com.ml.mall.bean.res.order.vo.OrderChangeArrVO;
import com.ml.mall.bean.res.vo.SupplierOrderVO;
import com.ml.mall.bean.res.vo.VariantVO;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.detail.SysOrderDetail;
import com.ml.mall.entity.msg.SysOrderMsg;
import com.ml.mall.entity.order.SysOrder;
import com.ml.mall.entity.state.SysOrderState;
import com.ml.mall.entity.supplier.SysOrderSupplier;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.entity.variant.SysProductVariant;
import com.ml.mall.enums.RetStatusNum;
import com.ml.mall.enums.SysSeqNameEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.msg.SysOrderMsgMapper;
import com.ml.mall.mapper.order.SysOrderMapper;
import com.ml.mall.mapper.state.SysOrderStateMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.common.CommonSeqService;
import com.ml.mall.service.company.SysCompanyLogisticsInfoService;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.deduct.SysADeductService;
import com.ml.mall.service.detail.SysOrderDetailService;
import com.ml.mall.service.order.SysOrderService;
import com.ml.mall.service.supplier.SysOrderSupplierService;
import com.ml.mall.service.shopping.SysShoppingCartService;
import com.ml.mall.service.tax.TaxService;
import com.ml.mall.service.variant.SysProductVariantPicService;
import com.ml.mall.service.variant.SysProductVariantSalesService;
import com.ml.mall.service.variant.SysProductVariantService;
import com.ml.mall.service.variant.SysProductVariantSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
* <p>
    *  服务实现类
    * </p>
*
* @author kyyang
* Created 2021-05-24
*/
@Service
@Slf4j
public class SysOrderServiceImpl extends ServiceImpl<SysOrderMapper, SysOrder> implements SysOrderService {

    @Autowired
    private SysOrderMapper sysOrderMapper;

    @Autowired
    private CommonSeqService commonSeqService;

    @Autowired
    private SysOrderStateMapper sysOrderStateMapper;

    @Autowired
    private SysOrderMsgMapper sysOrderMsgMapper;

    @Autowired
    private SysOrderDetailService sysOrderDetailService;

    @Autowired
    private SysProductVariantService sysProductVariantService;

    @Autowired
    private TaxService taxService;

    @Autowired
    private SysADeductService sysADeductService;


    @Autowired
    private SysShoppingCartService sysShoppingCartService;

    @Autowired
    private SysCompanyLogisticsInfoService sysCompanyLogisticsInfoService;

    @Autowired
    private SysProductVariantSkuService sysProductVariantSkuService;

    @Autowired
    private SysProductVariantSalesService sysProductVariantSalesService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    @Lazy
    private SysOrderSupplierService sysOrderSupplierService;

    @Autowired
    private SysProductVariantPicService sysProductVariantPicService;

    @Autowired
    private SysOrderCoupponService sysOrderCoupponService;
    @Autowired
    private SysCreditRecordService sysCreditRecordService;

     @Autowired
    private SysOrderDeliveryService sysOrderDeliveryService;


    @Autowired
    private OrderMailServiceImplAsyn orderMailServiceImplAsyn;

    @Autowired
    private SysCouponRecordService sysCouponRecordService;


    @Autowired
    private SysOrderAddrService sysOrderAddrService;

    @Resource
    private SysCouponRecordMapper sysCouponRecordMapper;

    @Autowired
    private SysCreditService sysCreditService;

    @Autowired
    private SysOrderStateService sysOrderStateService;

    @Autowired
    private SysOrderMsgService sysOrderMsgService;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysPayinfoService sysPayinfoService;

    @Override
    public Map<String, String> sysOrderNew(OrderNewReq orderNewReq) throws NoSuchAlgorithmException {
        log.info("=======begin");
        //购物车为空，直接返回
        ShoppingCartQueryRes shoppingCartQueryRes = sysShoppingCartService.queryProduct2Cart();
        if(null == shoppingCartQueryRes
                || null == shoppingCartQueryRes.getSupplierOrders()
                || shoppingCartQueryRes.getSupplierOrders().size() < 1){
            return null;
        }

        SysUser currentUser = JwtUtil.getCurrentUser();
        Long oid = commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_ORDER.getCode(), 2);
        SysOrder sysOrder = new SysOrder();
        sysOrder.setOid(oid);
        sysOrder.setInvoiceId("IVC-" + oid);
        sysOrder.setState(0); //默认是0；
        if(orderNewReq.getCreateTime() != null){
            sysOrder.setCreateAt(orderNewReq.getCreateTime());
        }
        //获取购物车价钱
        if (shoppingCartQueryRes == null) {
            throw new BizException(RetStatusNum.CART_ERROR.getCode(), RetStatusNum.CART_ERROR.getMessage());
        }
        //信用额度
        sysOrder = countCreditUse(sysOrder,orderNewReq.getUseCredit() == 1);
        //优惠券
        sysOrder = setCoupponInfo(orderNewReq,shoppingCartQueryRes.getSupplierOrders(),sysOrder);
        //设置总数量；总运费；创建订单明细
        List<SysOrderDetail> orderDetailList = createOrderDetail(shoppingCartQueryRes, sysOrder);

        //使用优惠券或者credit直接减钱 不管税
        sysOrder.setCompanyId(currentUser.getCompanyId());
        sysOrder.setCompanyName(currentUser.getCompanyName());
        sysOrder.setBuyerAcc(currentUser.getName()+" "+currentUser.getLastName());
        sysOrder.setAdaptFee(shoppingCartQueryRes.getSubAdjustment());
        sysOrder.setTaxFee(shoppingCartQueryRes.getSubTaxFee());
        //存储的总价是要加运费的；还要进行算法计算；随意订单详情里面的总费用与结账页面的总费用显示是不一样的
        BigDecimal orderAllFee = shoppingCartQueryRes.getSubTotalFee().add(sysOrder.getDeliveryFee());
        sysOrder.setSubFee(orderAllFee);
        //判断余额是否有余
        BigDecimal needPay=BigDecimal.ZERO;
        if(sysOrder.getCreditMoney().compareTo(sysOrder.getSubFee().subtract(sysOrder.getCouponMoney()))==-1){
            needPay = sysOrder.getSubFee().subtract(sysOrder.getCreditMoney()).subtract(sysOrder.getCouponMoney());
        }else {
            sysOrder.setCreditMoney(sysOrder.getSubFee().subtract(sysOrder.getCouponMoney()));
        }
        sysOrder.setTruePay(needPay);
        sysOrder.setProductFee(shoppingCartQueryRes.getSubTotalFee());
        int insert = sysOrderMapper.insert(sysOrder);
        Map<String, String> orderPay = null;
        if(insert > 0){
            //创建订单状态；
            createOrderState(oid.toString(),0);
            //创建买家留言
            createOrderMsg(oid, orderNewReq);
            //创建订单地址
            sysOrderAddrService.createOrderAdd(oid, currentUser.getCompanyId());
            //清空购物车
            sysShoppingCartService.clearCart();
            SysCompany currentCompany = sysCompanyMapper.selectByCompanyId(currentUser.getCompanyId());
            if(CommonConsts.NEED_PAY.equals(currentCompany.getNeedPay())){
                //根据订单号和费用创建订单支付信息,将格式化的支付信息返回前端表单提交
                orderPay = sysPayinfoService.createOrderPay(oid, needPay, currentUser);
            }
        }
        //todo：测试使用：正常是需要支付之后才能创建credit 扣款
        //创建使用余额记录;
        createCreditRecord(sysOrder);
        //创建卖家订单
        sysOrderSupplierService.createSupplierOrder(oid);
        //发送邮件；
        SendOrderEmail(sysOrder,orderDetailList,currentUser);
        return orderPay;
    }
    public List<SysOrderDetail> createOrderDetail(ShoppingCartQueryRes shoppingCartQueryRes,SysOrder sysOrder){
        List<SysOrderDetail> orderDetailList = new ArrayList<>();
        Long totalQty = 0L;
        BigDecimal deliveryFee = BigDecimal.ZERO;
        if (shoppingCartQueryRes != null && shoppingCartQueryRes.getSupplierOrders().size() > 0) {
            for (SupplierOrderVO supOrder : shoppingCartQueryRes.getSupplierOrders()) {
                if (supOrder.getVariants() != null && supOrder.getVariants().size() > 0) {
                    for (VariantVO vo : supOrder.getVariants()) {
                        SysOrderDetail sysOrderDetail = new SysOrderDetail();
                        sysOrderDetail.setVariantId(vo.getVariantId());
                        sysOrderDetail.setOid(sysOrder.getOid());
                        sysOrderDetail.setQuantity(vo.getQuantity().intValue());
                        SysProductVariant sysProductVariant = sysProductVariantService.getSysProductVariant(sysOrderDetail.getVariantId());
                        totalQty += vo.getQuantity();
                        if (sysProductVariant == null) {
                            continue;
                        }
                        //查询该sku是否具备限时促销
                        if (vo.getSellPrice() != null) {
                            sysOrderDetail.setIsSales(1);
                        }
                        sysOrderDetail.setVariantName(vo.getVariantName());
                        sysOrderDetail.setPicUrl(vo.getPicUrl());
                        sysOrderDetail.setSupplierCode(supOrder.getSupplierCode());
                        BeanUtils.copyProperties(vo,sysOrderDetail);
                        sysOrderDetail.setBuyunit(vo.getUom());
                        sysOrderDetail.setAllmoney(vo.getSubFee());
                        sysOrderDetail.setSupplierId(sysProductVariant.getSupplierId());
                        sysOrderDetail.setProductId(sysProductVariant.getProductId());
                        orderDetailList.add(sysOrderDetail);
                    }
                    //运费直接累加；购物车已经判断是否有运费
                    deliveryFee = deliveryFee.add(supOrder.getDeliveryFee());
                }
            }
            if (orderDetailList.size() > 0) {
                boolean flag=sysOrderDetailService.saveBatch(orderDetailList);
                System.out.print(flag);
            } else {
                throw new BizException(RetStatusNum.CART_ERROR.getCode(), RetStatusNum.CART_ERROR.getMessage());
            }
        }
        //设置一些参数并返回
        sysOrder.setAllQuantity(totalQty.intValue());
        sysOrder.setDeliveryFee(deliveryFee);
        return orderDetailList;
    }
    //发送邮件
    public void SendOrderEmail(SysOrder sysOrder,List<SysOrderDetail> orderDetailList,SysUser currentUser){
        OrderMailTemplateVO orderMailTemplateVO = orderMailTemplateVO(sysOrder);
        List<SellerOrderDetailArrVO> sellerOrderDetailArrVOS = setOrderArrVO(orderDetailList);
        orderMailTemplateVO.setOrderArr(sellerOrderDetailArrVOS);
        //发送邮件
        //注入优惠券
        setCouppon(orderMailTemplateVO);
        orderMailServiceImplAsyn.sysOrderNewMailAsyn(currentUser, orderMailTemplateVO);
    }

    private void setCouppon(OrderMailTemplateVO orderMailTemplateVO){
        //查询使用的优惠劵
        QueryWrapper<SysCouponRecord> w3 = new QueryWrapper();
        w3.eq("oid", orderMailTemplateVO.getOid());
        List<CupponDetailVO> cupponDetailVOList=sysCouponRecordService.cupponDetailVOList(orderMailTemplateVO.getOid(),null);
        //全局订单的优惠券的集合
        List<CupponDetailVO> buyersCouponVoList = new ArrayList<>();
        //卖家订单的优惠券的集合
        HashMap<Long,List<CupponDetailVO>> map=new HashMap<>();
        if (null != cupponDetailVOList && cupponDetailVOList.size() > 0) {
            cupponDetailVOList.stream().forEach(it -> {
                //判断是否为全局优惠券（没有SupplierId即视为全局优惠券）
                if (null == it.getSysCouponRecord().getSupplierId() || "".equals(it.getSysCouponRecord().getSupplierId())) {
                    buyersCouponVoList.add(it);
                }else {
                    if(map.containsKey(it.getSysCouponRecord().getSupplierId())){
                        map.get(it.getSysCouponRecord().getSupplierId()).add(it);
                    }else {
                        List<CupponDetailVO> list=new ArrayList<>();
                        list.add(it);
                        map.put(it.getSysCouponRecord().getSupplierId(),list);
                    }
                }
            });
            orderMailTemplateVO.setCupponVOList(buyersCouponVoList);
            if(null != orderMailTemplateVO.getOrderArr() && orderMailTemplateVO.getOrderArr().size()>0){
                orderMailTemplateVO.getOrderArr().stream().forEach(it->{
                    if(map.get(it.getSupplierId()) != null){
                        it.setCupponVOList(map.get(it.getSupplierId()));
                    }
                });
            }
        }
    }

    //设置优惠券相关
    private SysOrder setCoupponInfo(OrderNewReq orderNewReq, List<SupplierOrderVO> supplierOrderVOS,SysOrder sysOrder){
        BigDecimal couponMoney = BigDecimal.ZERO;
        Integer flag = 0;
        if (orderNewReq.getCupponCodes() != null && orderNewReq.getCupponCodes().size() > 0) {
            if (!StringUtils.isEmpty( orderNewReq.getCupponCodes().get(0) )) {
                CouponListCheckReq couponListCheckReq = new CouponListCheckReq();
                couponListCheckReq.setCouponCodeList(orderNewReq.getCupponCodes());
                //查询优惠券是否可以使用
                CoupponCheckRes coupponCheckRes = sysOrderCoupponService.checkCouponByCouponCode(couponListCheckReq);
                if (coupponCheckRes.getCanUseTogether() == true) {
                    //查询对应有优惠券累加；
                    couponMoney = sysOrderCoupponService.countCoupponMoneyAndCreatCoupponRecode
                            (supplierOrderVOS, orderNewReq.getCupponCodes(), sysOrder.getOid());
                    flag = 1;
                } else {
                    throw new BizException(CommonEnum.COUPPON_ERROR);
                }
            }
        }
        sysOrder.setHaveCoupon(flag);
        sysOrder.setCouponMoney(couponMoney);
        return sysOrder;
    }
    //计算额度使用
    private SysOrder countCreditUse(SysOrder sysOrder,Boolean useCredit){
        //设置使用的余额
        BigDecimal creditBalance = BigDecimal.ZERO;
        if(useCredit){
            CreditRecordQueryDto dto = new CreditRecordQueryDto();
            dto.setCompanyId(sysOrder.getCompanyId());
            //特殊sql没有就是0
            creditBalance = sysCreditRecordService.getCompanyCredit(dto);
        }
        sysOrder.setCreditMoney(creditBalance);
        return sysOrder;
    }

    /**
     * @description: 创建买家留言
     * @author kyyang
     * @date 2021/5/26 23:05
     * @version 1.0
     */
    private void createOrderMsg(Long oid, OrderNewReq orderNewReq) {
        SysOrderMsg sysOrderMsg = new SysOrderMsg();
        sysOrderMsg.setOid(oid);
        sysOrderMsg.setBuyerMsg(orderNewReq.getMsg());
        sysOrderMsgMapper.insert(sysOrderMsg);
    }

    /**
     * @description: 创建订单状态
     * @author kyyang
     * @date 2021/5/26 23:02
     * @version 1.0
     */
    private void createOrderState(String oid,Integer state) {
        SysOrderState sysOrderState = new SysOrderState();
        sysOrderState.setOid(oid);
        sysOrderState.setStateChageAt(new Date());
        sysOrderState.setState(state);
        sysOrderStateMapper.insert(sysOrderState);
    }

    private Long curOrderMs(List<OrderDetailVO> detail) {
        Long totalQty = 0L;
        if (detail != null && detail.size() > 0) {
            totalQty = detail.stream().collect(Collectors.summingLong(OrderDetailVO::getQuantity));
        }
        return totalQty;
    }
    @Override
    @Transactional
    public int sysOrderEdit(OrderEditReq orderEditReq) {
        LambdaQueryWrapper<SysOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(orderEditReq.getId() != null, SysOrder::getId, orderEditReq.getId())
                .eq(orderEditReq.getOid() != null, SysOrder::getOid, orderEditReq.getOid());

        SysOrder dbOrder = sysOrderMapper.selectOne(queryWrapper);
        Integer newOrderState = Integer.valueOf(orderEditReq.getState());
        //订单状态变更时，添加状态变更记录
        if(!dbOrder.getState().equals(newOrderState)){
            sysOrderStateService.createOrderState(StrUtil.toString(orderEditReq.getOid()), newOrderState);
        }

        SysOrder entity = new SysOrder();
        entity.setState(newOrderState);

        log.info("orderEditReq==={}",orderEditReq);
        log.info("entity==={}",entity);
        //TODO
        return sysOrderMapper.update(entity, queryWrapper);
    }

    private void createCreditRecord(SysOrder sysOrder) {
        if(sysOrder.getCreditMoney().compareTo(BigDecimal.ZERO) == 1){
            CreditRecordNewDto creditRecordNewDto = new CreditRecordNewDto();
            creditRecordNewDto.setType(CreditEnum.CREDIT_USE.getType());
            creditRecordNewDto.setChangeMoney(sysOrder.getCreditMoney());
            creditRecordNewDto.setCompanyId(sysOrder.getCompanyId());
            creditRecordNewDto.setChangeId(sysOrder.getOid());
            creditRecordNewDto.setOid(sysOrder.getOid());
            sysCreditRecordService.createCreditRecord(creditRecordNewDto);
        }
    }
    @Override
    public Page<OrderQueryPageRes> sysOrderByPage(OrderQueryPageReq req) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        if(!CommonConsts.ROLE_TYPE_ADMIN.equals(currentUser.getRoleType())){
            req.setCompanyId(currentUser.getCompanyId());
        }
        //分页查询结果
        List<OrderQueryPageRes> records = sysOrderMapper.selectPageOrder(req);
        //查询总数
        Integer total = sysOrderMapper.selectPageCount(req);

        Page<OrderQueryPageRes> resultPage = new Page<>(req.getPageIndex(), req.getPageNum());
        resultPage.setRecords(records);
        resultPage.setTotal(total);
        return resultPage;
    }
    @Override
    public OrderQueryOneRes sysOrderBuyerQuery_one(BaseBeanReq req) {
        SysOrder sysOrder = sysOrderMapper.selectById(req.getId());
        OrderQueryOneRes orderQueryOneRes = new OrderQueryOneRes();
        if (sysOrder == null) {
            return orderQueryOneRes;
        }
        BeanUtils.copyProperties(sysOrder, orderQueryOneRes);
        orderQueryOneRes.setReduceMoneyAll(orderQueryOneRes.getCouponMoney().add(orderQueryOneRes.getCreditMoney()));
        //查询订单留言
        QueryWrapper<SysOrderMsg> sysOrderMsgQueryWrapper=new QueryWrapper<>();
        sysOrderMsgQueryWrapper.eq("oid",sysOrder.getOid());
        List<SysOrderMsg> sysOrderMsgs = sysOrderMsgService.list(sysOrderMsgQueryWrapper);
        if(null != sysOrderMsgs && sysOrderMsgs.size()>0){
            orderQueryOneRes.setDeliveryNote(sysOrderMsgs.get(0));
        }
        //查询订单状态
        QueryWrapper<SysOrderState> w1 = new QueryWrapper<>();
        w1.eq("oid", sysOrder.getOid().toString());
        w1.orderByAsc("state_chage_at");
        List<SysOrderState> sysOrderStates = sysOrderStateMapper.selectList(w1);
        List<OrderChangeArrVO> orderChangeArrVOS = new ArrayList<>();
        if (sysOrderStates != null && sysOrderStates.size() > 0) {
            for (SysOrderState s : sysOrderStates) {
                OrderChangeArrVO entity = new OrderChangeArrVO();
                SpringUtil.copyPropertiesIgnoreNull(s, entity);
                orderChangeArrVOS.add(entity);
            }
        }
        orderQueryOneRes.setOrderChangeArr(orderChangeArrVOS);

        //根据订单号查询卖家订单
        QueryWrapper<SysOrderSupplier> w2 = new QueryWrapper();
        w2.eq("oid", sysOrder.getOid());
        List<SysOrderSupplier> sysOrderSuppliers = sysOrderSupplierService.list(w2);
        List<OrderArrVO> orderArrVOS = new ArrayList<>();
        if (sysOrderSuppliers != null && sysOrderSuppliers.size() > 0) {
            for (SysOrderSupplier sysOrderSupplier : sysOrderSuppliers) {
                OrderArrVO v = new OrderArrVO();
                SpringUtil.copyPropertiesIgnoreNull(sysOrderSupplier, v);
                v.setSupplierCompanyName(sysOrderSupplier.getSupplierCode());
                QueryWrapper<SysOrderDelivery> w33 = new QueryWrapper<>();
                w33.eq("supplier_oid",sysOrderSupplier.getSupplierOid());
                List<SysOrderDelivery> list = sysOrderDeliveryService.list(w33);
                if(list!=null&&list.size()>0){
                    v.setOrderDeliveryArr(list);
                }
                orderArrVOS.add(v);
            }
        }
        if (orderArrVOS.size() > 0) {
            for (OrderArrVO vo : orderArrVOS) {
                //填充卖家信息
                setOrderArrVO(vo, sysOrder);
            }
        }
        orderQueryOneRes.setOrderArr(orderArrVOS);

        return orderQueryOneRes;
    }
    @Override
    public SysOrder selectOrderByOid(Long oid) {
        QueryWrapper<SysOrder> w1 = new QueryWrapper<>();
        w1.eq("oid", oid);
        SysOrder sysOrder = sysOrderMapper.selectOne(w1);
        return sysOrder;

    }

    private void setOrderArrVO(OrderArrVO vo, SysOrder sysOrder) {
        //根据订单号+卖家ID 查询商品明细
        QueryWrapper<SysOrderDetail> w3 = new QueryWrapper<>();
        w3.eq("oid", sysOrder.getOid());
        w3.eq("supplier_id", vo.getSupplierId());
        List<SysOrderDetail> sysOrderDetails = sysOrderDetailService.list(w3);
        List<OrderDetailArrVO> orderDetailArrVOS = new ArrayList<>();
        if (sysOrderDetails != null && sysOrderDetails.size() > 0) {
            for (SysOrderDetail s : sysOrderDetails) {
                OrderDetailArrVO v = new OrderDetailArrVO();
                SpringUtil.copyPropertiesIgnoreNull(s, v);
                v.setAllMoney(s.getAllmoney());
                orderDetailArrVOS.add(v);
            }
        }
        vo.setOrderDetailArr(orderDetailArrVOS);
    }

    //买家生成订单发送邮件需要的数据
    public OrderMailTemplateVO orderMailTemplateVO(SysOrder sysOrder) {
        OrderMailTemplateVO orderMailTemplateVO=new OrderMailTemplateVO();

        BeanUtils.copyProperties(sysOrder, orderMailTemplateVO);
        orderMailTemplateVO.setReduceMoneyAll(orderMailTemplateVO.getCouponMoney().add(orderMailTemplateVO.getCreditMoney()));
        //查询订单状态
        QueryWrapper<SysOrderState> w1 = new QueryWrapper<>();
        w1.eq("oid", sysOrder.getOid());
        w1.orderByAsc("state_chage_at");
        List<SysOrderState> sysOrderStates = sysOrderStateMapper.selectList(w1);
        List<OrderChangeArrVO> orderChangeArrVOS = new ArrayList<>();
        if (sysOrderStates != null && sysOrderStates.size() > 0) {
            for (SysOrderState s : sysOrderStates) {
                OrderChangeArrVO entity = new OrderChangeArrVO();
                SpringUtil.copyPropertiesIgnoreNull(s, entity);
                orderChangeArrVOS.add(entity);
            }
        }
        orderMailTemplateVO.setOrderChangeArr(orderChangeArrVOS);
        return orderMailTemplateVO;
    }

    @Override
    public Map<String, String> orderPaymentDataQuery(OrderPaymentDataQueryDto dto) throws NoSuchAlgorithmException {
        SysUser currentUser = JwtUtil.getCurrentUser();
        //获取数据库中的支付信息，计算支付请求数据
        SysPayinfo payinfo = sysPayinfoService.queryByPayId(dto.getOid());
        return SdkIpay88Utils.doRequestToIpay88(payinfo, currentUser);
    }

    @Override
    public SysCompany orderCompanyQuery(Long oid) {
        return sysOrderMapper.selectOrderCompanyByOid(oid);
    }

    private List<SellerOrderDetailArrVO> setOrderArrVO(List<SysOrderDetail> list) {
        HashMap<Long,List<OrderProductDetailVO>> map=new HashMap<>();
        list.stream().forEach(it->{
            OrderProductDetailVO orderProductDetailVO=new OrderProductDetailVO();
            if(map.containsKey(it.getSupplierId())){
                BeanUtils.copyProperties(it,orderProductDetailVO);
                map.get(it.getSupplierId()).add(orderProductDetailVO);
            }else {
                List<OrderProductDetailVO> orderProductDetailVOList=new ArrayList<>();
                BeanUtils.copyProperties(it,orderProductDetailVO);
                orderProductDetailVOList.add(orderProductDetailVO);
                map.put(it.getSupplierId(),orderProductDetailVOList);
            }
        });
        List<SellerOrderDetailArrVO> sellerOrderDetailArrVOList=new ArrayList<>();
        map.keySet().forEach(it->{
            SellerOrderDetailArrVO sellerOrderDetailArrVO=new SellerOrderDetailArrVO();
            sellerOrderDetailArrVO.setSupplierId(it);
            sellerOrderDetailArrVO.setSupplierCompanyName(map.get(it).get(0).getSupplierCode());
            sellerOrderDetailArrVO.setOrderDetailArr(map.get(it));
            sellerOrderDetailArrVOList.add(sellerOrderDetailArrVO);
        });
        return sellerOrderDetailArrVOList;
    }
}
